package id.co.shuba.spamobile;

import id.co.shuba.spamobile.activities.LoginActivity;
import android.app.Application;
import android.content.Intent;
import android.os.CountDownTimer;
import android.util.Log;

public class CustomSessionApplication extends Application {
	private SessionCounter timer;
	private long timeOut = 60 * 60 * 1000;	
	 
	public void setTimeInMinute(int minute) {
		timeOut = minute * 60 * 1000;
	}
	
	@Override
    public void onCreate()
    {
		Log.d("CustomSessionApplication", "onCreate");
        super.onCreate();
                
        createTimer();        
    }	
	
	public void createTimer() {
		timer = new SessionCounter(timeOut,1000);
        timer.start();
	}
	
	@Override
	public void onTerminate() {
		Log.d("CustomSessionApplication", "onTerminate");
		super.onTerminate();
	}

    public void touch()
    {    	
    	timer.cancel();
    	createTimer();
    }
    
    public void stop() {
    	if (timer != null)
    		timer.cancel();
    }

    public class SessionCounter extends CountDownTimer {    	
        public SessionCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }              

        @Override
        public void onFinish() {     
        	Log.d("Sessions Timeout", "Finish is called");
        	Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("id.co.shuba.spamobile.ACTION_LOGOUT");
            sendBroadcast(broadcastIntent);           
            /*
            Intent loginActivityIntent = new Intent(CustomSessionApplication.this, LoginActivity.class);            
            startActivity(loginActivityIntent);*/
        }               

        @Override
        public void onTick(long millisUntilFinished) {
        	/*
        	if (App.DEBUG)
        		System.out.println("Timer  : " + (millisUntilFinished/1000));
        		*/
        }
    }
}
